package com.train.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter({"/page/success.html"})//对这/static/page/success.html进行过滤
public class LoginFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //向上转型（强制类型转换）
        HttpServletRequest request1=(HttpServletRequest)request;
        HttpServletResponse response1=(HttpServletResponse)response;

      /*  Cookie[] cookies = request1.getCookies();
        String username=null;
        String password=null;
        if(cookies!=null){
            for(Cookie cookie:cookies){
                String name = cookie.getName();
                if("username".equals(name)){
                    username = cookie.getValue();
                }else if("password".equals(name)){
                    password=cookie.getValue();
                }
            }
        }*/

        //获取Session对象
        HttpSession session = request1.getSession();
        Object user = session.getAttribute("user");

        if(user==null){
            //重定向到登陆页面
            response1.sendRedirect("/train/login.html");
        }else{
            //对请求进行放行
            chain.doFilter(request,response);
        }
    }
}
